package middlewares

import (
	"encoding/json"
	"io/ioutil"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

/**
 * 解析JSON、XML等参数中间件，且将参数添加到PostForm
 * @param http.HandlerFunc next ----------------------------------------------必传
 * @return http.HandlerFunc
 * @author huwl
 */
func ParseArgsMiddleware(ctx *gin.Context) {
	contentType := ctx.Request.Header.Get("Content-Type")
	if strings.Contains(contentType, "application/json") {
		var params map[string]interface{}
		body, _ := ioutil.ReadAll(ctx.Request.Body)
		json.Unmarshal(body, &params)
		ctx.Request.ParseForm()
		for k, v := range params {
			switch v.(type) {
			case string, float64, int, int64:
				ctx.Request.PostForm.Add(k, cast.ToString(v))
				ctx.Request.Form.Add(k, cast.ToString(v))
				ctx.Request.URL.Query().Add(k, cast.ToString(v))

			case []interface{}:
				for _, val := range v.([]interface{}) {
					switch val.(type) {
					case map[string]interface{}:
						value, _ := json.Marshal(val)
						ctx.Request.PostForm.Add(k, string(value))
						ctx.Request.Form.Add(k, string(value))

						ctx.Request.URL.Query().Add(k, cast.ToString(v))
					default:
						ctx.Request.PostForm.Add(k, cast.ToString(val))
						ctx.Request.Form.Add(k, cast.ToString(val))

						ctx.Request.URL.Query().Add(k, cast.ToString(v))
					}
				}
			}
		}
	}

}
